package com.ls.lserp.modules.produce.web;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.produce.entity.ProduceParameter;
import com.ls.lserp.modules.produce.service.ProduceParameterService;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.DictUtils;
import freemarker.template.Configuration;
import groovy.util.ResourceException;

/**
 * @ClassName: ProduceParameterController
 * @Description: 生产参数
 * 
 * @author	秦玉峰
 * @date 2017年3月31日 下午18:40:00
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/produce/procedure/")
public class ProduceParameterController extends BaseController {

	
	@Autowired
	private ProduceParameterService produceparameterservice;
	@Autowired
	Configuration freemarkerConfiguration;
	// 画面区分
		private static final String IMAGE_FLG="specimenDemandCreate";
	
	// 子项session
	private final String FINANCESUBLIST = "financeSubList";	
	@ModelAttribute
	public ProduceParameter get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {
			// 执行查询语句 查询基本信息
			return produceparameterservice.get(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new ProduceParameter();
		}
	}
	
	/**
	 * 生产参数一览画面
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = { "" })
	public String produceParameter() {

		return "modules/produce/produceParameter";

	}
	
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param produceparameter
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("produce:procedure:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(ProduceParameter produceparameter, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "produceparameter");

		// 画面取得的检索项目
		// 款式类别
		String styleCategoryCD = produceparameter.getStyleCategoryCD();
		// 工序号
		String itemCd = produceparameter.getItemCd();

		String strUri = request.getContextPath() + Global.getAdminPath();
		// 拼接字符串供分页使用
		String searchParam = "&itemCd=" + itemCd + "&styleCategoryCD=" + styleCategoryCD;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);

		// 查询一览页面数据
		Page<ProduceParameter> page = produceparameterservice.findList(new Page<ProduceParameter>(request, response), produceparameter);
		
		// 读取系统路径
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("dicts", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("ProduceParameter.ftl"), map);
		listMap.put("produceparameter", strHtml);
		listMap.put("page", page.getHtml());

			// ajax返回结果
			return renderString(response, listMap);
		}
	
	/**
	 * 进入编辑页面
	 * 
	 * @param produceparameter
	 * @param model
	 * @return
	 */
	@RequiresPermissions("produce:procedure:edit")
	@RequestMapping(value = "form")
	public String form(ProduceParameter produceparameter, RedirectAttributes redirectAttributes, Model model, HttpSession session,
			HttpServletRequest request, HttpServletResponse response) {

		// 款式类别
		List<Dict> produceparaList = DictUtils.getDictList(ResourcesUtil.getConfig("produceparaList"));
		// 新建判断 若不为null 编辑数据
		if (produceparameter.getId() != null) {

			// 实力化子项实体类
			ProduceParameter dictSub = new ProduceParameter();

			// 给子项实体类赋值（关联值——项目值）
			dictSub.setItemCd(produceparameter.getItemCd());

		} else {
			// 清空创建的子项
			session.setAttribute(FINANCESUBLIST, new ArrayList<Dict>());
		}
		produceparameter.preInsert();
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("produceparameter", produceparameter);
		model.addAttribute("produceparaList", produceparaList);
		// 返回页面地址
		return "modules/produce/produceParameterEdit";
	}
	
	/**
	 * 进入check页面
	 * 
	 * @param itemCd
	 * @param itemSort
	 * @return
	 */
	/*@RequiresPermissions("produce:procedure:edit")
	@ResponseBody
	@RequestMapping(value = "checkName")
	public String checkName(String itemCd,String styleCategoryCD,ProduceParameter produceparameter) {
		
		String shirt="STYLE_CATEGORY";
		String suit="PRODUCEPARALIST";
		// 判断id是否为null （判断新建或修改）
		if (produceparameter.getId() == null) {
        try {
        	// 页面获取数据值与旧数据若相同，并且数据值不为null
            if (styleCategoryCD.toUpperCase().equals(suit.toUpperCase()) && produceparameterservice.getItemCodeFin(itemCd) == null) {
            	
            	// 数据值未重名
        		return "true";
            }else if(styleCategoryCD.toUpperCase().equals(shirt.toUpperCase()) && produceparameterservice.getItemCodeFin(itemCd) == null){
            	
            	// 数据值未重名
        		return "true";
            }           
        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
        }
		
		// 数据值重名
		return "false";
		}else{
			return "true";
		}		
	}*/
	
	

	/**
	 * 保存信息
	 * 
	 * @param produceparameter
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws ResourceException
	 */
	@RequiresPermissions("produce:procedure:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(ProduceParameter produceparameter, HttpServletRequest request, Model model, HttpServletResponse response) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		if (IMAGE_FLG.equals(produceparameter.getImageFlg())) {
			try {
				// 保存数据
				produceparameterservice.saveProduce(produceparameter);
				listMap.put("proId",produceparameter.getId());
				listMap.put("saveFlg","true");
			} catch (Exception e) {
				listMap.put("saveFlg","false");
			}
		} else {
		// 判断id是否为null （判断新建或修改）
		if (produceparameter.getId() != null) {
			// 编辑数据
			// 判断数据是否删除
			ProduceParameter dictNew = get(produceparameter.getId().toString());
			// 判断数据是否删除
			if (dictNew == null || BaseEntity.DEL_FLAG_DELETE.equals(dictNew.getDeleteFlag())) {
				// 返回提示信息
				return renderString(response,
						AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}

			// 排他处理
			if (produceparameter.getVersion() == get(produceparameter.getId().toString()).getVersion()) {

				// 版本号加1
				produceparameter.setVersion(produceparameter.getVersion() + 1);
			} else {

				// 返回提示信息
				return renderString(response,
						AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}
		} else {

			// 新建版本号赋值1
			produceparameter.setVersion(1L);
		}

		// 保存基准数据及子项数据
		produceparameterservice.saveProduce(produceparameter);
		// 保存成功返回提示信息
		return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "dictSaveSuccess")));
		}
		// ajax返回结果
		return renderString(response,listMap);
	}
	
	/**
	 * 进入查看页面
	 * 
	 * @param produceparameter
	 * @param model
	 * @return
	 */
	@RequiresPermissions("produce:procedure:view")
	@RequestMapping(value = "show")
	public String show(ProduceParameter produceparameter, Model model) {

		model.addAttribute("produceparameter", produceparameter);
		// 返回页面地址
		return "modules/produce/produceParameterShow";
	}
	
	/**
	 * 删除信息
	 * 
	 * @param produceparameter
	 * @param response
	 * @return
	 */
	@RequiresPermissions("produce:procedure:edit")
	@RequestMapping(value = "delete")
	public String delete(ProduceParameter produceparameter, HttpServletResponse response) {

		try {

			// 执行逻辑删除方法
			produceparameterservice.deleteProduce(produceparameter);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 提示错误信息
			return renderString(response, AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		}

		// 提示删除成功信息
		return renderString(response, AjaxDone.ok(getText("dict_delete_success")));
	}
	
}
